#!/usr/bin/env python
"""
微信聊天助手冒烟测试运行脚本
"""
import os
import sys
import argparse
import asyncio
import subprocess
import logging
from datetime import datetime

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    handlers=[logging.StreamHandler()]
)
logger = logging.getLogger("run_smoke_test")

def check_environment():
    """检查环境配置"""
    # 检查微信是否运行
    try:
        import psutil
        wechat_running = False
        for proc in psutil.process_iter(['name']):
            if proc.info['name'] and 'WeChat' in proc.info['name']:
                wechat_running = True
                break
        
        if not wechat_running:
            logger.warning("未检测到微信正在运行，请先启动微信并登录")
            return False
    except ImportError:
        logger.warning("未安装psutil模块，无法检测微信是否运行")
    
    # 检查数据库文件是否存在
    from tests.smoke_test_config import SMOKE_TEST_CONFIG
    db_url = SMOKE_TEST_CONFIG["database"]["url"]
    if db_url.startswith("sqlite:///./"):
        db_file = db_url.replace("sqlite:///./", "")
        if not os.path.exists(db_file) and not SMOKE_TEST_CONFIG["database"].get("create_tables", False):
            logger.warning(f"数据库文件 {db_file} 不存在，且未配置自动创建表")
            return False
    
    return True

def run_smoke_test(args):
    """运行冒烟测试"""
    # 记录开始时间
    start_time = datetime.now()
    logger.info(f"开始执行冒烟测试，时间: {start_time.strftime('%Y-%m-%d %H:%M:%S')}")
    
    try:
        # 检查环境
        if not check_environment():
            if not args.force:
                logger.error("环境检查失败，使用 --force 参数可以强制执行测试")
                return False
            else:
                logger.warning("环境检查失败，但使用了 --force 参数强制执行测试")
        
        # 导入并执行测试模块
        from tests.smoke_test import run_smoke_tests
        success = asyncio.run(run_smoke_tests())
        
        # 记录结束时间和执行时间
        end_time = datetime.now()
        elapsed_time = (end_time - start_time).total_seconds()
        logger.info(f"冒烟测试执行完成，耗时: {elapsed_time:.2f} 秒")
        
        # 如果需要生成报告，生成HTML报告
        if args.report:
            generate_report(success, start_time, end_time, elapsed_time)
        
        return success
    
    except Exception as e:
        logger.error(f"执行冒烟测试时发生异常: {e}")
        return False

def generate_report(success, start_time, end_time, elapsed_time):
    """生成测试报告"""
    try:
        report_dir = "./reports"
        os.makedirs(report_dir, exist_ok=True)
        
        report_file = os.path.join(report_dir, f"smoke_test_report_{start_time.strftime('%Y%m%d_%H%M%S')}.html")
        
        # 读取日志文件内容
        from tests.smoke_test_config import SMOKE_TEST_CONFIG
        log_file = SMOKE_TEST_CONFIG["logging"].get("file")
        log_content = ""
        if log_file and os.path.exists(log_file):
            with open(log_file, "r", encoding="utf-8") as f:
                log_content = f.read()
        
        # 生成简单的HTML报告
        with open(report_file, "w", encoding="utf-8") as f:
            f.write(f"""<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>微信聊天助手冒烟测试报告</title>
    <style>
        body {{ font-family: Arial, sans-serif; margin: 20px; }}
        .header {{ background-color: #f0f0f0; padding: 10px; border-radius: 5px; }}
        .success {{ color: green; }}
        .failure {{ color: red; }}
        .log {{ background-color: #f8f8f8; padding: 10px; border: 1px solid #ddd; overflow: auto; max-height: 500px; }}
        pre {{ white-space: pre-wrap; }}
    </style>
</head>
<body>
    <div class="header">
        <h1>微信聊天助手冒烟测试报告</h1>
        <p><strong>开始时间:</strong> {start_time.strftime('%Y-%m-%d %H:%M:%S')}</p>
        <p><strong>结束时间:</strong> {end_time.strftime('%Y-%m-%d %H:%M:%S')}</p>
        <p><strong>耗时:</strong> {elapsed_time:.2f} 秒</p>
        <p><strong>结果:</strong> <span class="{'success' if success else 'failure'}">{("通过" if success else "失败")}</span></p>
    </div>
    
    <h2>测试日志</h2>
    <div class="log">
        <pre>{log_content}</pre>
    </div>
</body>
</html>""")
        
        logger.info(f"测试报告已生成: {report_file}")
        
    except Exception as e:
        logger.error(f"生成测试报告失败: {e}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="微信聊天助手冒烟测试运行脚本")
    parser.add_argument(
        "--report", 
        action="store_true", 
        help="生成HTML测试报告"
    )
    parser.add_argument(
        "--force", 
        action="store_true", 
        help="强制执行测试，忽略环境检查错误"
    )
    
    args = parser.parse_args()
    
    # 将当前目录添加到Python路径
    sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))
    
    # 运行测试
    success = run_smoke_test(args)
    
    # 根据测试结果设置退出码
    sys.exit(0 if success else 1) 